/**
 * @Title: UploadToTempSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月24日 上午10:42:21
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.google.gson.GsonBuilder;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.AppGlobal;
import com.jason.fingerprint.beans.BaseBean;
import com.jason.fingerprint.beans.WorkVisitBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.DateFormat;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.configs.DataConfig;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.utils.CharUtils;
import com.jason.fingerprint.utils.CodecUtils;
import com.jason.fingerprint.utils.DataUtils;
import org.kymjs.aframe.core.KJException;
import org.kymjs.aframe.utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: UploadToTempSyncLogic
 * @Description: 资源上传
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月24日 上午10:42:21
 */
public class UploadToTempSyncLogic extends Logic {

	public static class SERVICE{
		//(单文件上传) 新增日常报到的记录。
		public static final int SERVICE_DAILY_REPORT = 1;
		//(多文件上传) 新增个别教育、个别劳动签到记录时用到的照片
		public static final int SERVICE_COMMUNITY_SINGLE = 2;
		//(多文件上传) 上传 照片、录音 （集中活动）
		public static final int SERVICE_COMMUNITY_IMPLODE = 3;
		//(多文件上传) （新增走访记录）将走访的签到记录上传到平台。
		public static final int SERVICE_WORK_VISIT = 4;
		//(单文件上传) 外出请假（记录上传） 上传图片
		public static final int SERVICE_LEAVE_OUT = 5;
	}

	private static final String TAG = "UploadToTempSyncLogic";

	private Handler mHandler;
	private boolean mIsCallBack = false;// 是否有回调，此需要Handle,默认不回调
	private Message mMessage;
	private int mServiceId;
	private List<ImageOrAudioBean> mImageOrAudioBeans = new ArrayList<ImageOrAudioBean>();
	private int mSize = -1;// 总共要上传的条数
	private int mIndex = 0;// 上传到第几条

	private String mSponsorType; // 活动类型（0-集中教育 1-集中劳动 2-个别教育 3-个别劳动）
//	private String mSponsorId; // 活动ID(集中劳动、集中教育)
	
	public UploadToTempSyncLogic() {

	}

	public UploadToTempSyncLogic(AppContext appContext, Handler handler) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
	}

	public UploadToTempSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
	}

	public UploadToTempSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack, int serviceId) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
		this.mServiceId = serviceId;
	}

//	public UploadToTempSyncLogic(AppContext appContext, Handler handler,
//			boolean isCallBack, int serviceId, String sponsorType, String sponsorId) {
//		this(appContext, handler, isCallBack, serviceId);
//		this.mSponsorType = sponsorType;
//		this.mSponsorId = sponsorId;
//	}
	
	public UploadToTempSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack, String sponsorType) {
		this(appContext, handler, isCallBack, 2);
		this.mSponsorType = sponsorType;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#execute()
	 */
	@Override
	public void execute() {
		// TODO Auto-generated method stub
		StringBuilder where = new StringBuilder();
		if (!StringUtils.isEmpty(mSponsorType)) {
			if (mSponsorType.equals(DataConfig.REGISTER_TYPE_2)
					|| mSponsorType.equals(DataConfig.REGISTER_TYPE_3)) {
				mServiceId = SERVICE.SERVICE_COMMUNITY_SINGLE;
			}else {
				mServiceId = SERVICE.SERVICE_COMMUNITY_IMPLODE;
			}
			where.append("sponsorType = '");
			where.append(mSponsorType);
			where.append("'");
			where.append(" and ");
		}
		where.append("serviceId = ");
		where.append(mServiceId);
		where.append(" and state = 1");
		Log.i(TAG, "---execute--where:" + where.toString());
		mImageOrAudioBeans = mKjdb.findAllByWhere(ImageOrAudioBean.class,
				where.toString());
		mSize = -1;
		mIndex = 0;
		if (mImageOrAudioBeans != null && !mImageOrAudioBeans.isEmpty()) {
			mSize = mImageOrAudioBeans.size();
//			uploadSource();
			upload();
		} else {
			mMessage.what = UIHelper.FILE_UPLOAD_SUCCESS;
			send();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#send()
	 */
	@Override
	public void send() {
		// TODO Auto-generated method stub
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}
	}


	private void upload(){
		Map<String ,String> params = new HashMap<String, String>();
		Map<String ,File> fileParams = new HashMap<String, File>();
		if (mIndex >= mSize) {
			mMessage.what = UIHelper.FILE_UPLOAD_SUCCESS;
			send();
			return;
		}
		final ImageOrAudioBean audioBean = mImageOrAudioBeans.get(mIndex);
		if (audioBean == null) {
			mIndex ++ ;
//			uploadSource();
			upload();
			return;
		}
		put(AppGlobal.HTTP_PARAM_IMEI, mImei, params);
		String fileName = audioBean.getFileName();
		if (audioBean.getFileType() == 1) {
			fileName = fileName;
		}else {
			fileName += ".wav";
		}
		put("fileInputFileName", fileName, params);
		put("type", String.valueOf(audioBean.getFileType() == 1 ? 0 : 1), params);
		try {
			Log.i(TAG, "----->path:" + audioBean.getFilePath());
			fileParams.put("fileInput", new File(audioBean.getFilePath()));
		} catch (Exception e){
			e.printStackTrace();
		}
		if (mServiceId == SERVICE.SERVICE_DAILY_REPORT) {
			// (单文件上传)新增日常报到的记录。
			put("rymcId", audioBean.getParentId(), params);
			put("startTime", DataUtils.converDatLongToString(
					audioBean.getCreateDate(), DateFormat.DATE_YMD_HMS),params);
			put("endTime", DataUtils.converDatLongToString(
					audioBean.getUploadDate(), DateFormat.DATE_YMD_HMS),params);
			put("serviceId", String.valueOf(mServiceId), params);
		} else if (mServiceId == SERVICE.SERVICE_COMMUNITY_SINGLE) {
			// (多文件上传)上传 照片、录音 （个别活动）-----(多文件上传)新增个别教育、个别劳动签到记录时用到的照片
			put("serviceId", String.valueOf(mServiceId), params);
			put("eduComId", audioBean.getSponsorId(), params);
		} else if (mServiceId == SERVICE.SERVICE_COMMUNITY_IMPLODE) {
			// (多文件上传)-----(多文件上传)上传 照片、录音 （集中活动）
			if (audioBean.getRegistrationType() == 2 || audioBean.getRegistrationType() == 1){
				put("eduComId", audioBean.getSponsorId(), params);
				put("serviceId", String.valueOf(SERVICE.SERVICE_COMMUNITY_SINGLE), params);
			}else {
				put("serviceId", String.valueOf(SERVICE.SERVICE_COMMUNITY_IMPLODE), params);
				put("sponsorId", audioBean.getSponsorId(), params);
			}
		} else if (mServiceId == SERVICE.SERVICE_WORK_VISIT) {
			// (多文件上传)（新增走访记录）将走访的签到记录上传到平台。
			put("serviceId", String.valueOf(mServiceId), params);
			String parenId = audioBean.getParentId();
			WorkVisitBean visitBean = mKjdb.findById(parenId,
					WorkVisitBean.class);
			if (visitBean != null) {
				if (visitBean.getWorkId() != 0) {
					put("id", String.valueOf(visitBean.getWorkId()), params);
				} else {
					mIndex++;
//					uploadSource();
					upload();
					return;
				}
			} else {
				mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
				send();
				return;
			}

		} else if (mServiceId == SERVICE.SERVICE_LEAVE_OUT) {
			// (单文件上传)外出请假（记录上传）上传图片----(单文件上传)外出请假（记录上传）上传图片
			put("serviceId", String.valueOf(mServiceId), params);
			put("signTyp", audioBean.getSignType(), params);
			put("id", audioBean.getParentId(), params);
		}
		String url = HttpConfig.POST_URL_FILEUPLOAD_UPLOADTOTEMP;
		new PostFile(url,params,fileParams,new PostFile.CallBack(){

			@Override
			public void onSuccess(Object object) {
				Log.i(TAG, "----->arg0:" + object.toString());
				String result = null;
				BaseBean bean = null;
				try {
					result = CodecUtils.base64Decode(object.toString());
					Log.i(TAG, "----->Result:" + result);
					bean = new GsonBuilder().create().fromJson(result,
							BaseBean.class);
				} catch (Exception e) {
					mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
					send();
					return;
				}
				if (bean != null && bean.isSuccess()) {
					audioBean.setState(2);
					mKjdb.update(audioBean);
					mIndex++;
//					uploadSource();
					upload();
				} else {
					mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
					send();
				}
			}

			@Override
			public void onFailure(int arg1, String arg2) {
				Message message = mHandler.obtainMessage();
				if (arg1 == UIHelper.HTTP_CODE_TIMEOUT){
					message.what = UIHelper.HTTP_CODE_TIMEOUT;
				}else {
					message.what = UIHelper.FILE_UPLOAD_FAIL;
				}
				if (mIsCallBack){
					mHandler.sendMessage(mMessage);
					mMessage = mHandler.obtainMessage();
				}
			}
		}).start();

	}

	public Map<String ,String> put(String key, String value,Map<String ,String> params) {
		if (params == null){
			params = new HashMap<String, String>();
		}
		if (key != null) {
			if (!StringUtils.isEmpty(value)) {

				if (CharUtils.isChinese(value)) {
					params.put(key, CodecUtils.base64Encode(value));
				}else {
					params.put(key, value);
				}

			}
		} else {
			throw new KJException("key is NULL");
		}
		return params;
	}

//	// 上传资源
//	private void uploadSource() {
//		if (mIndex >= mSize) {
//			mMessage.what = UIHelper.FILE_UPLOAD_SUCCESS;
//			send();
//			return;
//		}
//		final ImageOrAudioBean audioBean = mImageOrAudioBeans.get(mIndex);
//		if (audioBean == null) {
//			mIndex ++ ;
////			uploadSource();
//			upload();
//			return;
//		}
//		mParams = new KJFileParams();
//		mParams.put(AppGlobal.HTTP_PARAM_IMEI, mImei);
//		mParams.put("serviceId", String.valueOf(mServiceId));
//		String fileName = audioBean.getFileName();
//		if (audioBean.getFileType() == 1) {
//			fileName += ".jpg";
//		}else {
//			fileName += ".amr";
//		}
//		mParams.put("fileInputFileName", fileName);
//		mParams.put("type", String.valueOf(audioBean.getFileType() == 1 ? 0 : 1));
//		FileInputStream stream = null;
//		try {
//			File file = new File(audioBean.getFilePath());
//			stream = new FileInputStream(file);
//			mParams.put("fileInput", stream, fileName);
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} finally {
//			if (stream != null){
//				try {
//					stream.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//		if (mServiceId == SERVICE.SERVICE_DAILY_REPORT) {
//			// (单文件上传)新增日常报到的记录。
//			mParams.put("rymcId", audioBean.getParentId());
//			mParams.put("startTime", DataUtils.converDatLongToString(
//					audioBean.getCreateDate(), DateFormat.DATE_YMD_HMS));
//			mParams.put("endTime", DataUtils.converDatLongToString(
//					audioBean.getUploadDate(), DateFormat.DATE_YMD_HMS));
//		} else if (mServiceId == SERVICE.SERVICE_COMMUNITY_SINGLE) {
//			// (多文件上传)上传 照片、录音 （个别活动）-----(多文件上传)新增个别教育、个别劳动签到记录时用到的照片
//			mParams.put("eduComId", audioBean.getSponsorId());
//		} else if (mServiceId == SERVICE.SERVICE_COMMUNITY_IMPLODE) {
//			// (多文件上传)-----(多文件上传)上传 照片、录音 （集中活动）
//			mParams.put("sponsorId", audioBean.getSponsorId());
//		} else if (mServiceId == SERVICE.SERVICE_WORK_VISIT) {
//			// (多文件上传)（新增走访记录）将走访的签到记录上传到平台。
//			String parenId = audioBean.getParentId();
//			WorkVisitBean visitBean = mKjdb.findById(parenId,
//					WorkVisitBean.class);
//			if (visitBean != null) {
//				if (visitBean.getWorkId() != 0) {
//					mParams.put("id", String.valueOf(visitBean.getWorkId()));
//				} else {
//					mIndex++;
////					uploadSource();
//					upload();
//				}
//			} else {
//				mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
//				send();
//				return;
//			}
//
//		} else if (mServiceId == SERVICE.SERVICE_LEAVE_OUT) {
//			// (单文件上传)外出请假（记录上传）上传图片----(单文件上传)外出请假（记录上传）上传图片
//			mParams.put("signTyp", audioBean.getSignType());
//			mParams.put("id", audioBean.getParentId());
//		}
//		String url = HttpConfig.POST_URL_FILEUPLOAD_UPLOADTOTEMP;
//		Log.i(TAG, "----->API:" + url);
//		Log.i(TAG, "----->mParams:" + mParams.getParamString());
//		KJHttp kjHttp = new KJHttp();
//		kjHttp.post(url, mParams, new HttpCallBack() {
//
//			@Override
//			public void onSuccess(Object arg0) {
//				Log.i(TAG, "----->arg0:" + arg0.toString());
//				String result = null;
//				BaseBean bean = null;
//				try {
//					result = CodecUtils.base64Decode(arg0.toString());
//					Log.i(TAG, "----->Result:" + result);
//					bean = new GsonBuilder().create().fromJson(result,
//							BaseBean.class);
//				} catch (Exception e) {
//					mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
//					send();
//					return;
//				}
//				if (bean != null && bean.isSuccess()) {
//					audioBean.setState(2);
//					mKjdb.update(audioBean);
//					mIndex++;
////					uploadSource();
//					upload();
//				} else {
//					mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
//					send();
//				}
//			}
//
//			@Override
//			public void onLoading(long arg0, long arg1) {
//				Log.i(TAG, "----->Result:arg0:" + arg0 + ",arg1:" + arg1);
//			}
//
//			@Override
//			public void onFailure(Throwable arg0, int arg1, String arg2) {
//				Log.i(TAG, "----->Result:arg1:" + arg1 + ",arg2:" + arg2);
//				mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
//				send();
//			}
//		});
//
//	}

	/* (non-Javadoc)
	 * @see com.jason.fingerprint.logic.Logic#destory()
	 */
	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
